import { FilesModel } from '@/services/service'
import { getAllFiles } from '@/services'
import { listToTree } from '@/utils/translate'
import { loading } from '@/decorator/loading'
import { CURRENTFILE } from '@/types/constant'

interface IState {
  connection: boolean
  files: Array<FilesModel>
  fileMap: object
  fileTree: Array<object>
  currentFile: FilesModel
  [key: string]: any
}

const state: IState = {
  connection: false,
  files: [],
  fileMap: {},
  fileTree: [],
  set currentFile(val: FilesModel) {
    localStorage.setItem(CURRENTFILE, JSON.stringify(val))
  },
  get currentFile() {
    try {
      return JSON.parse(localStorage.getItem(CURRENTFILE) || '')
    } catch (error) {
      return {} as FilesModel
    }
  }
}

const mutations = {
  SET_CONNECTION: (state: IState, bool: boolean) => {
    state.connection = bool
  },
  SET_FILES: (state: IState, list: FilesModel[]) => {
    state.files = list
  },
  SET_FILEMAP: (state: IState, map: object) => {
    state.fileMap = map
  },
  SET_FILETREE: (state: IState, list: Array<object>) => {
    state.fileTree = list
  },
  SET_CURRENTFILE: (state: IState, file: FilesModel) => {
    state.currentFile = file
  }
}

class DbActions {
  constructor() {}

  public static connected({ commit }: any) {
    commit('SET_CONNECTION', true)
  }

  public static disConnect({ commit }: any) {
    commit('SET_CONNECTION', false)
  }

  @loading()
  public static async getFiles({ commit }: any) {
    let res = await getAllFiles()
    if (res.code) {
      let { tree, listMap } = listToTree(res.data)
      commit('SET_FILES', res.data)
      commit('SET_FILEMAP', listMap)
      commit('SET_FILETREE', tree)
    }
  }

  public static async setCurrentFile({ commit }: any, file: FilesModel) {
    commit('SET_CURRENTFILE', file)
  }
}

const actions = {
  connected: DbActions.connected,
  disConnect: DbActions.disConnect,
  getFiles: DbActions.getFiles,
  setCurrentFile: DbActions.setCurrentFile
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
